/*-----------------------------------------------------------------------------
* @Description:     权限管理列表
* @Version:         1.0.0
* @author:          zhangmengqi(1845955175@qq.com)
* @date             2017.11.08
* ==NOTES:=============================================
* v1.0.0(2017.11.08):
     初始生成
* ---------------------------------------------------------------------------*/
$(function(){
    /**
     * 初始化提示信息、验证表单
     */
    formValidatorAddForm();/*验证框开始就验证*/
    Pagination(1);/*分页刷数据*/
    var oldName;
    /*
     * 分页
     */
    $('#pageLimit').bootstrapPaginator({
        //currentPage: 3,
       /* totalPages: $('.pageCount').val(),*/
        size: "small",
        bootstrapMajorVersion: 3,
        alignment: "right",
        numberOfPages: 5,
        itemTexts: function (type, page, current) {
            switch (type) {
                case "first": return "首页";
                case "prev": return "<";
                case "next": return ">";
                case "last": return "末页";
                case "page": return page;
            }
        },
        onPageClicked: function (event, originalEvent, type, page) {
            var
                form = $(".J_searchForm").serializeObject();

            Pagination(page, form);  
        }
    });   

    /*
     * 表格编辑按钮
     */
    $(document).on('click', '.J_edit', function(e){
        var
            tr = $(e.target).parents('tr'),
            id = $(tr).attr('data-id'),
            userName = $(tr).attr('data-userName'),
            name = $(tr).attr('data-name'),
            password = $(tr).attr('data-password'),
            phoneNumber = $(tr).attr('data-phoneNumber');

        oldName = userName;
        $('.hidId').val(id);
        $('.J_editexpInput').val(userName);
        $('.J_editdesInput').val(name);
        $('.J_editphoInput').val(phoneNumber);
        $('.J_editPassword').val(password);
    });

    /**
     * 对话框编辑按钮
     */
    $('.J_editDlg').click(function(){
        formValidatorEditForm();
        var data = $('.J_editForm').data('bootstrapValidator');
        if (data) {
            data.validate();
            if (!data.isValid()) {
                return false;
            }    
        }
        edit();
    });    

    /**
     * 对话框添加按钮
     */
    $('.J_addDlg').click(function(){
        formValidatorAddForm();
        var data = $('.J_addForm').data('bootstrapValidator');
        if (data) {
        // 修复记忆的组件不验证
            data.validate();
            if (!data.isValid()) {
                return false;
            }
        }
        add();
    });

     /**
     * 添加对话框验证重名事件
     */
    $('.J_addexpInput').blur(function(){
        sendAddName();
    });

    /**
     * 添加对话框验证重名事件
     */
    $('.J_editexpInput').blur(function(){
        sendEditName();
    });

    /**
     * 批量删除按钮
     */
    // 全选 
    $(".J_allChk").click(function() { 
        $("input[name='subChk']").prop("checked",this.checked); 
    }); 
    // 单选 
    $(document).on('click',"input[name='subChk']",function() { 
        $(".J_allChk").prop("checked", $("input[name='subChk']").length == $("input[name='subChk']").filter(":checked").length ? true:false); 
    });
    /* 批量删除 */ 
    $(".J_allDel").click(function() { 
    // 判断是否至少选择一项 
        var checkedNum = $("input[name='subChk']:checked").length; 
        if(checkedNum == 0) { 
            $("#atLeastOne").modal('show'); 
            return; 
        }
        // 批量选择 
        else{
            $("#delAllDialog").modal('show');
            $(".J_delAllDlg").click(function(){
               var checkedList = new Array(); 
                $("input[name='subChk']:checked").each(function() { 
                    var tr = $(this).parents('tr'),
                        idList =  $(tr).attr('data-id');
                    checkedList.push(idList); 
                }); 
                $.ajax({ 
                    type: jQuery.url.AuthorityManagement.delAuthority.type,
                    url: jQuery.url.AuthorityManagement.delAuthority.url,
                    contentType: "application/x-www-form-urlencoded; charset=utf-8",
                    data: {'delitems':checkedList.toString()},
                    dataType: "json",
                    success: function(rs) {
                        $("#delAllDialog").modal('hide');
                        if(rs.code == 0){
                            $("input:checkbox").attr("checked", false); 
                            window.location.reload();
                        }else{
                            Alert("提示信息", "操作失败，返回参数不正确。")
                        }
                    },
                    error: function (message) {
                        $("#delAllDialog").modal('hide');
                        Alert("提示信息", "请求发送失败。")
                    }
                }); 
            }); 
        } ;
    }); 

    /**
     * 关闭添加对话框清除校验、数据
     */
    $('#addDialog').on('hidden.bs.modal', function() {
        $('.J_addForm').bootstrapValidator('resetForm', true);
        $(".J_addForm").data('bootstrapValidator').destroy();
        $('.J_addForm').data('bootstrapValidator', null);
        formValidatorAddForm();
    });
    /**
     * 关闭添加编辑框清除校验、数据
     */
    $('#editDialog').on('hidden.bs.modal', function() {
        $('.J_editForm').bootstrapValidator('resetForm', true);
        $(".J_editForm").data('bootstrapValidator').destroy();
        $('.J_editForm').data('bootstrapValidator', null);
    });
    /**
     * 分页刷数据
     */
    function Pagination(page, extraData){

        var
            currentPage = page,            
            str = '',
            data = {
                page: currentPage
            };
        // jQuery.extend(data, extraData);
        $.ajax({
            type: jQuery.url.AuthorityManagement.authorityList.type,
            url: jQuery.url.AuthorityManagement.authorityList.url,
            contentType: "application/json; charset=utf-8",
            data: data,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#J_template').empty();
                if(rs.code == 0){
                    $('#pageLimit').bootstrapPaginator({
                        totalPages: rs.pageDataCount
                    });
                    $.each(rs.list, function(index, item){
                        str += '<tr data-id="'+ item.id +'" data-userName="'+ item.userName +'" data-name="'+ item.name +'" data-phoneNumber="'+ item.phoneNumber +'" data-password="'+ item.password +'" >\
                                <td><input type="checkbox" name="subChk"/></th>\
                                <td>'+ item.userName +'</td>\
                                <td>'+ item.name +'</td>\
                                <td>'+ item.phoneNumber +'</td>\
                                <td>'+ item.password +'</td>\
                                <td>\
                                    <a href="#?id='+ item.id +'" class="label-info J_edit"  data-toggle="modal" data-target="#editDialog"><i class="fa fa-pencil"></i>&nbsp;编辑</a>\
                                </td>\
                            </tr>'
                    }); 
                    $('#J_template').append(str);
                }else{                
                    Alert("提示信息", "操作失败，返回参数不正确。")
                }
            },
            error: function (message) {
                Alert("提示信息", "请求发送失败。")
            }
        });
    }


    /**
     * 添加事件
     */
    function add(){
        var
            userName = $('.J_addexpInput').val(),
            name = $('.J_adddesInput').val(),
            phoneNumber = $('.J_addphoInput').val(),
            password = $('.J_password').val(),
            form = {
                userName: userName,
                name: name,
                phoneNumber:phoneNumber,
                password:password
            };

        $.ajax({
            type: jQuery.url.AuthorityManagement.addAuthority.type,
            url: jQuery.url.AuthorityManagement.addAuthority.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: form,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#addDialog').modal('hide');
                if( rs.code == 0){                   
                    location.reload();
                }else{                
                    Alert("提示信息", "操作失败，返回参数不正确。")
                }
            },
            error: function (message) {
                $('#addDialog').modal('hide');
                Alert("提示信息", "请求发送失败。")
            }
        });
    }

    /**
     * 编辑事件
     */
    function edit(){
        var
            page = $('#pageLimit li.active').text(),
            id = $('.hidId').val(),
            userName = $('.J_editexpInput').val(),
            name = $('.J_editdesInput').val(),
            phoneNumber = $('.J_editphoInput').val(),
            password = $('.J_editPassword').val(),
            form = {
                id: id,
                userName: userName,
                name: name,
                phoneNumber:phoneNumber,
                password:password
            };
            console.log(password);
        $.ajax({
            type: jQuery.url.AuthorityManagement.editAuthority.type,
            url: jQuery.url.AuthorityManagement.editAuthority.url,
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: form,     //JSON.stringify
            dataType: "json",
            success: function (rs) {
                $('#editDialog').modal('hide');
                if( rs.code == 0){                   
                    Pagination(page);
                }else{                
                    Alert("提示信息", "操作失败，返回参数不正确。")
                }
            },
            error: function (message) {
                $('#editDialog').modal('hide');
                Alert("提示信息", "请求发送失败。")
            }
        });
    }

    /**
     * 添加框验证
     */
    function formValidatorAddForm(){
        $('.J_addForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                userName: {
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        }
                    }
                },
                name: {
                    validators: {
                        notEmpty: {
                            message: '真实姓名不能为空'
                        }
                    }
                },
                phoneNumber: {
                    validators: {
                        notEmpty: {
                            message: '请输入正确的手机号'
                        },
                        stringLength: {
                            min:11,
                            max:11,
                            message: ' '
                        },
                        regexp: {
                            regexp: /^[0-9_\.]+$/,
                            message: ' '
                        }
                        
                    }
                },
                password: {
                    validators: {
                        notEmpty: {
                            message: '密码最少为6位'
                        },
                        stringLength: {
                            min:6,
                            message: ' '
                        }
                    }
                }
            }
        });
    }

    /**
     * 编辑框验证 
     */ 
    function formValidatorEditForm(){
        $('.J_editForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
                userName: {
                    validators: {
                        notEmpty: {
                            message: '用户名不能为空'
                        }
                    }
                },
                name: {
                    validators: {
                        notEmpty: {
                            message: '真实姓名不能为空'
                        }
                    }
                },
                phoneNumber: {
                    validators: {

                        notEmpty: {
                            message: '请输入正确的手机号'
                        },
                        stringLength: {
                            min:11,
                            max:11,
                            message: ' '
                        },
                        regexp: {
                            regexp: /^[0-9_\.]+$/,
                            message: ' '
                        }
                        
                    }
                },
                password: {
                    validators: {
                        notEmpty: {
                            message: '密码最少为6位'
                        },
                        stringLength: {
                            min:6,
                            message: ' '
                        }
                    }
                }
            }
        });
    }

    /**
     * 失焦发送添加用户名 
     */ 
    function sendAddName(){
        var
            name = $('.J_addexpInput').val();
        if(name){
            $.ajax({
                type: jQuery.url.AuthorityManagement.sendAddName.type,
                url: jQuery.url.AuthorityManagement.sendAddName.url,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                data: {name: name},     //JSON.stringify
                dataType: "json",
                success: function (rs) {
                    if( rs.code != 0){                   
                        Alert("提示信息", "操作失败，添加的用户名已存在。")
                    }
                },
                error: function (message) {
                    Alert("提示信息", "请求发送失败。")
                }
            });
        }else{
            return false;
        }
    }

    /**
     * 失焦发送编辑用户名 
     */
    function sendEditName(){
        var 
            newName = $('.J_editexpInput').val();
        if((oldName != newName) && newName){
            $.ajax({
                type: jQuery.url.AuthorityManagement.sendEditName.type,
                url: jQuery.url.AuthorityManagement.sendEditName.url,
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                data: {name: newName},     //JSON.stringify
                dataType: "json",
                success: function (rs) {
                    if( rs.code != 0){                   
                        Alert("提示信息", "操作失败，编辑的用户名已存在。");
                    }
                },
                error: function (message) {
                    Alert("提示信息", "请求发送失败。")
                } 
            });
        }
    }
});

